﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Globalization;
using System.Web.Hosting;

namespace mesoBoard.Web.Core
{
    public class mesoBoardVirtualPathProvider : VirtualPathProvider
    {
        private string GetThemePath()
        {
            return "Themes/" + HttpContext.Current.Items["mbThemeFolder"];
        }

        private string SanitizePath(string virtualPath)
        {
            virtualPath = virtualPath.Replace("{theme}", GetThemePath());
            virtualPath = virtualPath.Replace("{CTF}", "~/"+GetThemePath());
            return virtualPath;
        }

        public override string CombineVirtualPaths(string basePath, string relativePath)
        {
            relativePath = SanitizePath(relativePath); 
            basePath = SanitizePath(basePath);

            return base.CombineVirtualPaths(basePath, relativePath);
        }

        public override bool DirectoryExists(string virtualDir)
        {
            virtualDir = SanitizePath(virtualDir); 
            return base.DirectoryExists(virtualDir);
        }

        public override VirtualDirectory GetDirectory(string virtualDir)
        {
            virtualDir = SanitizePath(virtualDir); 
            return base.GetDirectory(virtualDir);
        }

        public override System.Web.Caching.CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            if (virtualPath.Contains("{theme}") || virtualPath.Contains("{CTF}"))
                return null;

            return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        } 

        public override bool FileExists(string virtualPath)
        {
            virtualPath = SanitizePath(virtualPath); 
            return base.FileExists(virtualPath);
        }

        public override VirtualFile GetFile(string virtualPath)
        {
            virtualPath = SanitizePath(virtualPath); 
            return base.GetFile(virtualPath);
        }
    }
}
